import { EventSystem } from "../../../../../Core/Module/EventSystem/EventSystem";
import { AwakeSystem } from "../../../../../Core/Module/EventSystem/IAwakeSystem";
import { DestroySystem } from "../../../../../Core/Module/EventSystem/IDestroySystem";
import { LoadSystem } from "../../../../../Core/Module/EventSystem/ILoadSystem";
import { Log } from "../../../../../Core/Module/Log/Log";
import { ExpandOf, FriendOf, GetTypeOf, ObjectSystemAttribute } from "../../../../../Decorator/Decorator";
import { AAIHandler } from "../../../../Model/Share/Module/AI/AAIHandler";
import { AIDispatcherComponent } from "../../../../Model/Share/Module/AI/AIDispatcherComponent";
import { AIHandlerAttribute } from "../../../../Model/Share/Module/AI/AIHandlerAttribute";

/**
 * 使用 Expand 扩展方法
 * 
 * 必须作出以下申明，才能调用对象的扩展方法
 */
declare module "../../../../Model/Share/Module/AI/AIDispatcherComponent" {

    interface AIDispatcherComponent {

        Load(): void;

    }

}

@ExpandOf(AIDispatcherComponent)
export class AIDispatcherComponentSystem {

    private static Load(self: AIDispatcherComponent): void {
        self.AIHandlers.Clear();

        let types = EventSystem.Instance.GetTypes(GetTypeOf(AIHandlerAttribute));
        for (let type in types) {
            let clazz = types[type];
            let obj = new clazz();
            let aaiHandler = obj as AAIHandler;
            if (aaiHandler == null) {
                Log.Error(`robot ai is not AAIHandler: ${type}`);
                continue;
            }
            self.AIHandlers.Add(type, aaiHandler);
        }
    }

}

@FriendOf(AIDispatcherComponent)
@ObjectSystemAttribute()
export class AIDispatcherComponentAwakeSystem extends AwakeSystem<AIDispatcherComponent> {

    Awake(self: AIDispatcherComponent): void {
        AIDispatcherComponent.Instance = self;
        self.Load();
    }

}

@FriendOf(AIDispatcherComponent)
@ObjectSystemAttribute()
export class AIDispatcherComponentLoadSystem extends LoadSystem<AIDispatcherComponent> {

    Load(self: AIDispatcherComponent): void {
        self.Load();
    }

}

@FriendOf(AIDispatcherComponent)
@ObjectSystemAttribute()
export class AIDispatcherComponentDestroySystem extends DestroySystem<AIDispatcherComponent> {

    Destroy(self: AIDispatcherComponent): void {
        self.AIHandlers.Clear();
        AIDispatcherComponent.Instance = null;
    }

}